package ink.xiaobaibai.serviceOxy.onePay.impl;

import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import ink.xiaobaibai.common.QiNiuCommon;
import ink.xiaobaibai.serviceOxy.onePay.IUploadService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * @description: 七牛云文件存储服务
 * @author: 小白白
 * @create: 2021-05-29
 **/

@Service
@Slf4j
public class QiniuUploadServiceImpl implements IUploadService {

    private String private_bucket = "krk-private";
    private String private_httpUrl = "http://pimage.kangrk.com/";
    public static String public_httpUrl = "http://image.kangrk.com/";
    private String public_bucket = "krk";

    private Auth auth;
    private Configuration cfg;
    private UploadManager uploadManager;
    private BucketManager bucketManager;

    public QiniuUploadServiceImpl() {
        this.auth = Auth.create(QiNiuCommon.accessKey, QiNiuCommon.secretKey);
        this.cfg = new Configuration(Region.huanan());
        this.uploadManager = new UploadManager(this.cfg);
        this.bucketManager = new BucketManager(this.auth, this.cfg);
    }

    @Override
    public String upload(String filePath, String myFileName) {
        log.info("七牛上传文件:" + filePath + ",文件名:" + myFileName);
        String upToken = this.auth.uploadToken(this.private_bucket);
        try {
            Response response = this.uploadManager.put(filePath, myFileName, upToken);
            //解析上传成功的结果
            /*DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);*/
        } catch (QiniuException ex) {
            Response r = ex.response;
            log.error(r.toString());
            try {
                log.error(r.bodyString());
            } catch (QiniuException ex2) {
                //ignore
            }
        }
        return this.private_httpUrl + myFileName;
    }

    @Override
    public String getPrivateUrl(String publicUrl) {
        /**
         * 300秒,请在5分钟内下载
         */
        return this.auth.privateDownloadUrl(publicUrl, 300);
    }

    @Override
    public void deleteFile(String fileName) {
        try {
            this.bucketManager.delete(this.private_bucket, fileName);
        } catch (QiniuException ex) {
            System.err.println(ex.code());
            System.err.println(ex.response.toString());
        }
    }

    @Override
    public String getQiniuToken() {
        return this.auth.uploadToken(this.public_bucket);
    }

}
